
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponseRedirect
from django.urls import reverse

from common.models import User


class UserAuthMiddleware(MiddlewareMixin):

    def process_request(self, request):

        if request.path in ['/user/login/', '/user/register/']:
            return None

        if 'user_id' in request.session:
            request.user = User.objects.filter(pk=request.session['user_id']).first()
            return None

        if request.path == '/user/index/':
            return None

        return HttpResponseRedirect(reverse('user:login'))


